using Digitalmes.Common.Interfaces;
using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.Consumptions.Commands;

/// <summary>
/// 解绑生产用料命令。
/// </summary>
/// <param name="Id">生产用料记录 Id</param>
public sealed record UnboundMaterialConsumptionCommand(long Id) : IRequest<IResult<bool>>;

internal sealed class UnboundMaterialConsumptionCommandHandler(IRepository<ProdMaterialConsumption> repo, ICurrentUser currentUser)
    : IRequestHandler<UnboundMaterialConsumptionCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UnboundMaterialConsumptionCommand request, CancellationToken cancellationToken)
    {
        var consumption = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (consumption == null)
        {
            return Result.Failure("未找到要生产用料信息");
        }

        if (consumption.IsUnbound)
        {
            return Result.Failure("生产用料已解绑");
        }

        consumption.IsUnbound = true;
        consumption.UnboundBy = currentUser.Username;
        consumption.UnboundTime = DateTime.Now;
        var ok = await repo.UpdateAsync(consumption, m => new
        {
            m.IsUnbound,
            m.UnboundBy,
            m.UnboundTime,
        }, cancellationToken);

        return Result.From(ok);
    }
}
